package ita.class1.group2.supermarket.merchant.controller;

import ita.class1.group2.supermarket.common.annotation.Autowired;
import ita.class1.group2.supermarket.common.annotation.Component;
import ita.class1.group2.supermarket.common.annotation.RequestMapping;
import ita.class1.group2.supermarket.common.auth.SecurityUtils;
import ita.class1.group2.supermarket.common.pojo.ResponseMessage;
import ita.class1.group2.supermarket.common.util.API;
import ita.class1.group2.supermarket.common.util.HttpUtil;
import ita.class1.group2.supermarket.common.util.JsonUtil;
import ita.class1.group2.supermarket.merchant.pojo.Product;
import ita.class1.group2.supermarket.merchant.pojo.StoreForm;
import ita.class1.group2.supermarket.merchant.pojo.User;
import ita.class1.group2.supermarket.merchant.service.ProductService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ProductController {

    @Autowired private ProductService productService;
    @Autowired private SecurityUtils securityUtils;

    @RequestMapping("/products")
    public List<Product> products() throws Exception {

        Map<String, String> reqParams = new HashMap<>();
        reqParams.put("USER_ID", ((User)securityUtils.getSubject().getAuthorizingInfo()).getId());
        String storeFormJson  = HttpUtil.doPost(API.GET_STORE_FORM, reqParams);


        if (!storeFormJson.isEmpty()) {
            StoreForm storeForm = JsonUtil.json2pojo(JsonUtil.obj2json(JsonUtil.json2pojo(storeFormJson, ResponseMessage.class).getContent()), StoreForm.class);
            return productService.findAllBySId(storeForm.getStore().getId());
        }

        return new ArrayList<Product>();
    }

}
